package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.entity.PaDonateGoods;
import cn.chinaflame.pagodas.repository.PaDonateGoodsRepository;
import cn.chinaflame.pagodas.req.PaDonateGoodsReq;
import cn.chinaflame.pagodas.utils.UpdateTool;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;

/**
 * Created by yw on 2018/10/12.
 */
@Service
public class PaDonatrGoodsService {

    private static final Logger logger = LoggerFactory.getLogger(PaDonatrGoodsService.class);
    @Autowired
    private PaDonateGoodsRepository paDonateGoodsRepository;
    @Autowired
    private IdGeneratorService idGeneratorService;

    public Object add (PaDonateGoods paDonateGoods) {
        logger.info("捐赠商品添加service paDonateGoods:{}",paDonateGoods);
        try {
            String id = idGeneratorService.generateIdByTableName("pa_donate_goods");
            paDonateGoods.setId(id);
            paDonateGoods.setStatus("0");
            paDonateGoods = paDonateGoodsRepository.save(paDonateGoods);
            return Result.create("");
        }catch (Exception e){
            logger.info("异常为：e:{}",e);
        }
        return Result.create("FALSE","添加失败");
    }

    public Object update (PaDonateGoods paDonateGoods) {
        logger.info("捐赠商品删除service paDonateGoods:{}",paDonateGoods);
        try {
            PaDonateGoods paDonateGoods1 = paDonateGoodsRepository.findOne(paDonateGoods.getId());
            UpdateTool.copyNullProperties(paDonateGoods1,paDonateGoods);
            BeanUtils.copyProperties(paDonateGoods,paDonateGoods1);
            paDonateGoods = paDonateGoodsRepository.save(paDonateGoods1);
            return Result.create(paDonateGoods);
        }catch (Exception e){
            logger.info("异常为：e:{}",e);
        }
        return Result.create("FALSE","删除失败");
    }

    public Object delete (String id) {
        logger.info("捐赠商品修改service id:{}",id);
        try {
            PaDonateGoods paDonateGoods = paDonateGoodsRepository.findOne(id);
            paDonateGoods.setStatus("1");
            paDonateGoodsRepository.saveAndFlush(paDonateGoods);
            return Result.create("OK","删除成功");
        }catch (Exception e){
            logger.info("异常为：e:{}",e);
        }
        return Result.create("FALSE","删除失败");
    }

    public Object list (PaDonateGoodsReq req) {
        logger.info("捐赠商品查询列表service req:{}",req);
        try{
            if (req.getPageIndex() == null || req.getPageSize() == null){
                List<PaDonateGoods> paDonateGoodsList = paDonateGoodsRepository.findAll(new Specification<PaDonateGoods>() {
                    @Override
                    public Predicate toPredicate(Root<PaDonateGoods> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                        List<Predicate> list = Lists.newArrayList();
                        if (!Strings.isNullOrEmpty(req.getId())) {
                            list.add(cb.equal(root.get("id").as(Strings.class),req.getId()));
                        }
                        if (!Strings.isNullOrEmpty(req.getName())) {
                            list.add(cb.like(root.get("name").as(String.class),"%"+req.getName()+"%"));
                        }
                        list.add(cb.equal(root.get("status").as(String.class),"0"));
                        Predicate[] p = new Predicate[list.size()];
                        return cb.and(list.toArray(p));
                    }
                });
                Map<String,Object> map = Maps.newHashMap();
                map.put("list",paDonateGoodsList);
                map.put("count",paDonateGoodsList.size());
            }
            Pageable pageable = new PageRequest(req.getPageIndex()-1,req.getPageSize(),new Sort(Sort.Direction.DESC,"id"));
            Page<PaDonateGoods> PaDonateGoodsList = paDonateGoodsRepository.findAll(new Specification<PaDonateGoods>() {
                @Override
                public Predicate toPredicate(Root<PaDonateGoods> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                    List<Predicate> list = Lists.newArrayList();
                    if (!Strings.isNullOrEmpty(req.getId())) {
                        list.add(cb.equal(root.get("id").as(Strings.class),req.getId()));
                    }
                    if (!Strings.isNullOrEmpty(req.getName())) {
                        list.add(cb.like(root.get("name").as(String.class),"%"+req.getName()+"%"));
                    }
                    list.add(cb.equal(root.get("status").as(String.class),"0"));
                    Predicate[] p = new Predicate[list.size()];
                    return cb.and(list.toArray(p));
                }
            },pageable);
            List<PaDonateGoods> list = PaDonateGoodsList.getContent();
            Map<String,Object> map = Maps.newHashMap();
            map.put("list",list);
            map.put("count",PaDonateGoodsList.getTotalElements());
            return Result.create(map);
        }catch (Exception e) {
            logger.info("错误为：e{}",e);
        }

        return Result.create("FALSE","查询失败");
    }

    public Object query (String id) {
        logger.info("捐赠商品查询service id:{}", id);
        try{
            if (Strings.isNullOrEmpty(id)) {
                return Result.create("FALSE", "捐赠商品编号不能为空");
            }
            PaDonateGoods paDonateGoods = paDonateGoodsRepository.findOne(id);
            if (paDonateGoods == null) {
                return Result.create("FALSE", "捐赠商品查询为空");
            }
            return Result.create(paDonateGoods);
        }catch (Exception e){
            logger.info("错误为 e:{}",e);
        }
        return Result.create("FALSE", "查看捐赠商品失败");
    }

    /**
     *
     * @param id        商品编号
     * @param number    下单数量
     * @param type      类型，1减库存，2加库存
     * @return
     */
    public Object stock (String id,int number,String type) {
        logger.info("商品下单减库存service id:{},number:{}",id,number);
        try{
            PaDonateGoods paDonateGoods = paDonateGoodsRepository.findOne(id);
            if ("1".equals(type)) {
                if (paDonateGoods.getStock() >= number) {
                    int stock = paDonateGoods.getStock() - number;
                    paDonateGoods.setStock(stock);
                    paDonateGoodsRepository.save(paDonateGoods);
                    return Result.create("OK", "商品下单减库存成功");
                }
                return Result.create("FALSE", "商品减库不足");
            }else if ("2".equals(type)){
                int stock = paDonateGoods.getStock() + number;
                paDonateGoods.setStock(stock);
                paDonateGoodsRepository.save(paDonateGoods);
                return Result.create("OK", "商品下单未支付恢复库存成功");
            }

        }catch (Exception e){
            logger.error("错误为 e:{}",e);
        }
        return Result.create("FALSE", "商品下单减库存失败");
    }


}
